import "./product.css"
import { useState, useEffect } from 'react';
import {
    Input, Select, Table, Card, Row, Col,
    Typography, Badge,
    Modal, Form, InputNumber, Checkbox, Image,
    Button,
    Tooltip,
    Skeleton
} from 'antd';
import {
    PlusOutlined, DownloadOutlined,
} from '@ant-design/icons';
import { UpdateProduct } from "../../component/product/updateProduct";
import { ProductDetails } from "../../component/product/productDetails";

import AddProduct from "../../component/product/AddProduct";

const { Title, Text } = Typography;
const { Option } = Select;


// 模拟数据
const productsData = {
    1: {
        id: 1,
        name: "推拿按摩",
        category: "理疗项目",
        categoryType: "treatment",
        price: 188.00,
        description: "60分钟专业推拿，缓解肌肉疲劳，疏通经络，促进血液循环。适合长期办公族、颈椎腰椎不适人群。",
        duration: 60,
        master: "all",
        masterName: "全部员工",
        effect: "缓解疲劳、疏通经络、促进血液循环",
        attention: "孕妇慎用，饭后1小时内不宜进行，皮肤有破损者不宜进行",
        mainImage: "https://picsum.photos/id/133/600/400",
        images: [
            "https://picsum.photos/id/134/600/400",
            "https://picsum.photos/id/135/600/400"
        ],
        status: "active",
        sort: 80,
        sales: 356,
        remarks: "需提前1天预约，周末及节假日价格上浮20%"
    },
    2: {
        id: 2,
        name: "针灸治疗",
        category: "理疗项目",
        categoryType: "treatment",
        price: 268.00,
        description: "专业员工针灸，调理身体机能，针对特定穴位进行治疗，效果显著。",
        duration: 45,
        master: "li,chen",
        masterName: "李员工、陈员工",
        effect: "止痛、调节内分泌、改善睡眠",
        attention: "孕妇禁用，有出血倾向者禁用，皮肤感染者禁用",
        mainImage: "https://picsum.photos/id/225/600/400",
        images: [
            "https://picsum.photos/id/226/600/400",
            "https://picsum.photos/id/227/600/400"
        ],
        status: "active",
        sort: 75,
        sales: 245,
        remarks: "需提前2天预约，治疗后24小时内避免洗澡"
    },
    3: {
        id: 3,
        name: "艾草精油",
        category: "中药产品",
        categoryType: "medicine",
        price: 88.00,
        description: "纯天然艾草提取，适合按摩使用，具有温经散寒、活血通络的功效。",
        stock: 42,
        unit: "瓶",
        origin: "河南南阳",
        expiry: 365,
        mainImage: "https://picsum.photos/id/106/600/400",
        images: [
            "https://picsum.photos/id/107/600/400",
            "https://picsum.photos/id/108/600/400"
        ],
        status: "active",
        sort: 60,
        sales: 156,
        remarks: "每瓶100ml，配合推拿效果更佳"
    },
    4: {
        id: 4,
        name: "颈椎按摩器",
        category: "养生器材",
        categoryType: "equipment",
        price: 399.00,
        description: "家用便携式，缓解颈椎疲劳，3种按摩模式，智能定时功能。",
        stock: 18,
        unit: "台",
        origin: "广东深圳",
        expiry: null,
        mainImage: "https://picsum.photos/id/118/600/400",
        images: [
            "https://picsum.photos/id/119/600/400",
            "https://picsum.photos/id/120/600/400"
        ],
        status: "active",
        sort: 50,
        sales: 67,
        remarks: "保修期1年，需使用USB充电"
    },
    5: {
        id: 5,
        name: "养生 herbal tea",
        category: "保健饮品",
        categoryType: "drink",
        price: 58.00,
        description: "多种草药配方，调理养生，适合日常饮用，具有清热解毒、健脾养胃的功效。",
        stock: 0,
        unit: "盒",
        origin: "浙江杭州",
        expiry: 180,
        mainImage: "https://picsum.photos/id/292/600/400",
        images: [
            "https://picsum.photos/id/293/600/400",
            "https://picsum.photos/id/294/600/400"
        ],
        status: "inactive",
        sort: 40,
        sales: 124,
        remarks: "每盒15袋，建议每日1-2袋，开水冲泡"
    },
    101: {
        id: 101,
        name: "推拿按摩套餐",
        category: "定制套餐",
        categoryType: "package",
        price: 498.00,
        description: "3次专业推拿 + 艾草精油1瓶，适合长期保健养生。",
        items: ["tuina", "aicao"],
        itemNames: ["推拿按摩", "艾草精油"],
        validity: 90,
        notes: "套餐有效期90天，需在有效期内使用完毕，不与其他优惠同享",
        mainImage: "https://picsum.photos/id/133/600/400",
        images: [
            "https://picsum.photos/id/134/600/400",
            "https://picsum.photos/id/135/600/400"
        ],
        status: "active",
        sort: 90,
        sales: 128,
        remarks: "购买后需电话预约首次服务时间"
    }
};


// 产品分类数据
const categories = [
    { type: "treatment", name: "理疗项目" },
    { type: "medicine", name: "中药产品" },
    { type: "equipment", name: "养生器材" },
    { type: "drink", name: "保健饮品" },
    { type: "package", name: "定制套餐" }
];


const Product = () => {
    // 状态管理
    const [products, setProducts] = useState(productsData);
    const [filteredProducts, setFilteredProducts] = useState(Object.values(productsData));
    const [currentCategory, setCurrentCategory] = useState("all");
    const [searchText, setSearchText] = useState("");
    const [statusFilter, setStatusFilter] = useState("all");
    const [priceSort, setPriceSort] = useState("");
    const [isAddMode, setIsAddMode] = useState(false);
    const [tableParams, setTableParams] = useState({
        pagination: {
            current: 1,
            pageSize: 10,
        },
    });
    const [isShow, set_isShow] = useState(true);
    setTimeout(() => {
        set_isShow(false);
    }, 2000);

    // 合并后的模态框状态
    const [modalVisible, setModalVisible] = useState(false);
    const [modalMode, setModalMode] = useState('view'); // 'view' 或 'edit'
    
    // 选中的产品ID
    const [productId, setProductId] = useState("");

 
    // 过滤和排序产品列表
    useEffect(() => {
        let result = Object.values(products);

        // 按分类过滤
        if (currentCategory !== "all") {
            result = result.filter(product => product.categoryType === currentCategory);
        }

        // 按搜索文本过滤
        if (searchText) {
            const text = searchText.toLowerCase();
            result = result.filter(product =>
                product.name.toLowerCase().includes(text) ||
                product.description.toLowerCase().includes(text)
            );
        }

        // 按状态过滤
        if (statusFilter != "all") {
            result = result.filter(product => product.status === statusFilter);
        }

        setFilteredProducts(result);
    }, [products, currentCategory, searchText, statusFilter, priceSort]);

    // 表格列定义
    const columns = [
        {
            title: '产品图片',
            dataIndex: 'name',
            key: 'name',
            ellipsis: {
                showTitle: false,
            },
            render: (text, record) => (
                <div style={{ display: "flex" }}>
                    <div >
                        <Image
                            src={record.mainImage}
                            alt={record.name}
                            width={48}
                            height={48}
                            preview={false}
                            className="rounded-md object-cover"
                        />
                    </div>
                </div>
            ),
        },
        {
            title: "产品名称",
            dataIndex: "name",
            key: "name",
            ellipsis: {
                showTitle: false,
            },
        },
        {
            title: "产品描述",
            dataIndex: "description",
            key: "description",
            ellipsis: {
                showTitle: false,
            },
            render: description => (
                <Tooltip placement="topLeft" title={description}>
                    {description}
                </Tooltip>
            ),
        },
        {
            title: '分类',
            dataIndex: 'category',
            key: 'category',
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',
            render: (price, record) => (
                <div>
                    <span className="text-accent font-medium">¥{price.toFixed(2)}</span>
                </div>
            ),
        },
      
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                if (status === 'active') {
                    return <Badge status="success" text="启用" />;
                } else if (status === 'inactive') {
                    return <Badge status="default" text="禁用" />;
                }
                return null;
            },
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 130,
            render: (_, record) => (
                <div style={{ display: "flex", gap: 10 }}>
                 
                    <Button
                        type="primary"
                        size="small"
                        onClick={() => handleOpenModal(record.id, 'view')}
                    >
                        详情
                    </Button>
                </div>
            ),
        },
    ];

    // 打开模态框（支持查看和编辑模式）
    const handleOpenModal = (id, mode) => {
        setProductId(id);
        setModalMode(mode);
        setModalVisible(true);
    };

    // 切换到编辑模式
    const handleSwitchToEdit = () => {
       
        setModalMode('edit');
    };

    // 取消编辑，返回查看模式
    const handleCancelEdit = () => {
        setModalMode('view');
    };

    // 保存编辑后返回查看模式
    const handleSaveEdit = () => {
        // 这里可以添加保存逻辑
        setModalMode('view');
    };

    // 处理新增产品
    const handleAddProduct = () => {
        setIsAddMode(true); 
    };

    // 处理分类变更
    const handleCategoryChange = (categoryType) => {
        setCurrentCategory(categoryType);
    };
  
    return (
        <div >
            {isShow ? (
                <Skeleton paragraph={{ rows: 10 }} active></Skeleton>
            ) : (
                <div>
                    <div style={{ width: "100%" }}>
                        <div style={{ display: "flex", marginBottom: 10, justifyContent: "space-between" }}>
                            <div style={{ width: 250 }}>
                                <Title level={2} className="text-secondary">产品管理</Title>
                                <Text type="secondary">管理理疗项目和相关产品</Text>
                            </div>
                            <div style={{ marginTop: "16px", display: "flex", gap: 10 }}>
                                <Button
                                    icon={<PlusOutlined />}
                                    onClick={handleAddProduct}
                                    className="btn-addProduct"
                                >
                                    新增产品
                                </Button>
                             
                            </div>
                        </div>


                        {/* 产品分类标签 */}
                        <Card style={{ marginBottom: 10 }}>
                            <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
                                <div
                                    onClick={() => handleCategoryChange("all")}
                                    className={currentCategory === "all" ? "check-item" : "nocheck-item"}
                                >
                                    全部产品
                                </div>
                                {categories.map(category => (
                                    <div
                                        key={category.type}
                                        onClick={() => handleCategoryChange(category.type)}
                                        className={currentCategory === category.type ? "check-item" : "nocheck-item"}
                                    >
                                        {category.name}
                                    </div>
                                ))}
                            </div>

                            {/* 搜索和筛选 */}
                            <div style={{ display: "flex", justifyContent: "space-between" }}>
                                <div style={{ width: "20%" }}>
                                    <Input
                                        placeholder="搜索产品名称..."
                                        prefix={<PlusOutlined />}
                                        value={searchText}
                                        onChange={(e) => setSearchText(e.target.value)}
                                    />
                                </div>
                                <div style={{ display: "flex", gap: 10 }}>
                                    <Select
                                        style={{ width: 120 }}
                                        value={statusFilter}
                                        onChange={setStatusFilter}
                                    >
                                        <Option value="all">全部状态</Option>
                                        <Option value="active">启用</Option>
                                        <Option value="inactive">禁用</Option>
                                    </Select>
                                </div>
                            </div>
                        </Card>

                        {/* 产品列表 */}
                        <Card className="mb-6">
                            <Table
                                bordered
                                columns={columns}
                                dataSource={filteredProducts}
                                rowKey="id"
                                pagination={tableParams.pagination}
                                rowClassName="table-row-hover"
                            />
                        </Card>
                    </div>

                    {/* 合并的产品详情/编辑模态框 */}
                    <Modal
                        style={{ top: "50px" }}
                        title={
                            <Title level={4} style={{ margin: 0 }}>
                                {modalMode === 'view' ? '产品详情' : '编辑产品'}
                            </Title>
                        }
                        open={modalVisible}
                        onCancel={() => setModalVisible(false)}
                        footer={modalMode === 'view' ? [
                            <Button
                                key="edit"
                                type="primary"
                                onClick={handleSwitchToEdit}
                            >
                                编辑
                            </Button>,
                            <Button
                                key="close"
                                onClick={() => setModalVisible(false)}
                                className="border border-gray-300"
                            >
                                关闭
                            </Button>
                        ] : [
                           
                        ]}
                        width={800}
                        destroyOnHidden
                    >
                        {modalMode === 'view' ? (
                            <ProductDetails id={productId} />
                        ) : (
                            <UpdateProduct id={productId} />
                        )}
                    </Modal>

                    {/* 新增产品模态框 */}
                    <Modal
                        style={{ top: "50px" }}
                        title={<Title>{"新增产品"}</Title>}
                        open={isAddMode}
                        onCancel={() => setIsAddMode(false)}
                        footer={[]}
                        width={700}
                        destroyOnHidden
                    >
                        <AddProduct />
                    </Modal>
                </div>
            )}
        </div>
    );
};

export default Product;
